package com.cn.intelligence.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cn.intelligence.mapper.AreasMapper;
import com.cn.intelligence.mapper.CitiesMapper;
import com.cn.intelligence.mapper.ProvincesMapper;
import com.cn.intelligence.mapper.TbAddressMapper;
import com.cn.intelligence.mapper.TbCartMapper;
import com.cn.intelligence.mapper.TbItemMapper;
import com.cn.intelligence.mapper.TbMUserMapper;
import com.cn.intelligence.mapper.TbOrderMapper;
import com.cn.intelligence.mapper.TbSendProductMapper;
import com.cn.intelligence.mapper.WuliuMapper;
import com.cn.intelligence.pojo.Areas;
import com.cn.intelligence.pojo.AreasExample;
import com.cn.intelligence.pojo.Cities;
import com.cn.intelligence.pojo.CitiesExample;
import com.cn.intelligence.pojo.EUDataGridResult;
import com.cn.intelligence.pojo.Provinces;
import com.cn.intelligence.pojo.ProvincesExample;
import com.cn.intelligence.pojo.TaotaoResult;
import com.cn.intelligence.pojo.TbAddress;
import com.cn.intelligence.pojo.TbCart;
import com.cn.intelligence.pojo.TbItem;
import com.cn.intelligence.pojo.TbItemExample;
import com.cn.intelligence.pojo.TbMUser;
import com.cn.intelligence.pojo.TbMUserExample;
import com.cn.intelligence.pojo.TbOrder;
import com.cn.intelligence.pojo.TbOrderExample;
import com.cn.intelligence.pojo.TbSendProduct;
import com.cn.intelligence.pojo.TbSendProductExample;
import com.cn.intelligence.pojo.Wuliu;
import com.cn.intelligence.service.OrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	public TbOrderMapper tbOrderMapper;
	@Autowired
	public TbAddressMapper tbAddressMapper;
	@Autowired
	public TbCartMapper tbCartMapper;
	
	@Autowired
	public TbItemMapper tbItemMapper;
	
	@Autowired
	private ProvincesMapper provincesMapper;
	@Autowired
	private CitiesMapper citiesMapper;
	@Autowired
	private AreasMapper areasMapper;
	@Autowired
	private WuliuMapper wuliuMapper;
	@Autowired
	private TbMUserMapper tbMUserMapper;
	@Autowired
	private TbSendProductMapper tbSenderProductMapper;


	/**
	 * 获取系统用户
	 */
	@Override
	public 	EUDataGridResult getOrders(Integer page, Integer rows, TbOrder order,String sfd,String etd,TbMUser user){
	
		TbOrderExample tbOrderExample = new TbOrderExample();
		TbOrderExample.Criteria crtteria = tbOrderExample.createCriteria();
		// 根据状态查询
		if(order.getStatus()!=null && !"".equals(order.getStatus())){
			crtteria.andStatusEqualTo(order.getStatus());
		}
		// 根据买家昵称查询
		if(order.getBuyerNick()!=null && !"".equals(order.getBuyerNick())){
			crtteria.andBuyerNickLike("%"+order.getBuyerNick()+"%");	
		}	
		// 根据推广人查询
		if(order.getSendRemark()!=null && !"".equals(order.getSendRemark())){
			crtteria.andBuyerMessageLike("%"+order.getSendRemark()+"%");	
		}
		
		// 根据订单号查询
		if(order.getOrderId()!=null && !"".equals(order.getOrderId())){
			crtteria.andOrderIdEqualTo(order.getOrderId());
		}
		// 根据订单创建时间查询
		if((sfd!=null && !"".equals(sfd))){
			crtteria.andCreateTimeGreaterThanOrEqualTo(new DateTime(sfd).toDate());
		}
		if((etd!=null && !"".equals(etd))){
			crtteria.andCreateTimeLessThanOrEqualTo(new DateTime(etd).toDate());
		}
		//根据用户角色查询数据
		if(!"1".equals(user.getRole())){
			TbSendProductExample senderProduct = new TbSendProductExample();
			TbSendProductExample.Criteria criteria = senderProduct.createCriteria();
			criteria.andUidEqualTo(user.getId());
			 List<TbSendProduct> orderlist = tbSenderProductMapper.selectByExample(senderProduct);
			 List<String> orders=new ArrayList<String>();
			 for (TbSendProduct tbSendProduct : orderlist) {
				 orders.add(tbSendProduct.getOrderId().toString());
			}
			 crtteria.andOrderIdIn(orders);
		}

		
		tbOrderExample.setOrderByClause("create_time DESC");

		// 分页查询
		PageHelper.startPage(page, rows);
		List<TbOrder> tbOrderList = tbOrderMapper.selectByExampleWithBLOBs(tbOrderExample);
		for (TbOrder tbOrder : tbOrderList) {
			if(!"".equals(tbOrder.getShippingName()) &&tbOrder.getShippingName()!=null){
				Wuliu wuliu = wuliuMapper.selectByPrimaryKey(Long.parseLong(tbOrder.getShippingName()));
				if(wuliu!=null){
					tbOrder.setShippingName(wuliu.getName());
				}
			}
			
		}
		
		// 获取总数
		PageInfo<TbOrder> pageInfo = new PageInfo<TbOrder>(tbOrderList);
		// 实现返回值设定
		EUDataGridResult euDataGridResult = new EUDataGridResult();
		euDataGridResult.setRows(tbOrderList);
		euDataGridResult.setTotal(pageInfo.getTotal());
		return euDataGridResult;

	}

	/**
	 * 获取收货人地址
	 */
	
	@Override
	public TaotaoResult selectuserAddress(Integer addressId) {
		TbAddress address = tbAddressMapper.selectByPrimaryKey(addressId);
		Map<String,Object> map = new HashMap<String,Object>();
		//根据ID查询地址名称
		// 查询省份
		ProvincesExample provincesExample = new ProvincesExample();
		ProvincesExample.Criteria provincecriteria = provincesExample.createCriteria();
		provincecriteria.andProvinceidEqualTo(address.getProvice());
		List<Provinces> plist= provincesMapper.selectByExample(provincesExample);
		if(plist!=null && plist.size()>0){
			map.put("pName", plist.get(0).getProvince());	
		}
		// 查询市区
		CitiesExample citiesExample = new CitiesExample();
		CitiesExample.Criteria citescriteria = citiesExample.createCriteria();
		citescriteria.andCityidEqualTo(address.getCity());
		List<Cities> clist = citiesMapper.selectByExample(citiesExample);
		if(clist!=null && clist.size()>0){
			map.put("cName", clist.get(0).getCity());	
		}
		// 查询区域
		AreasExample areasExample = new AreasExample();
		AreasExample.Criteria areascriteria = areasExample.createCriteria();
		areascriteria.andAreaidEqualTo(address.getArea());
		List<Areas> alsit = areasMapper.selectByExample(areasExample);	
		if(alsit!=null && alsit.size()>0){
			map.put("aName", alsit.get(0).getArea());	
		}

		map.put("adds", address);
		
		return TaotaoResult.ok(map);
	}

	@Override
	public String updateOrderStatus(String [] ids) throws Exception {
		List<String> errorIdlist = new ArrayList<String>();
		for (String orderId : ids) {
			// 修改订单状态
			TbOrder tbOrder= tbOrderMapper.selectByPrimaryKey(orderId);
			if(tbOrder.getStatus()!=7){
				errorIdlist.add(tbOrder.getOrderId());
				continue;
			}
			tbOrder.setOrderId(orderId);
			tbOrder.setPaymentTime(new Date());
			tbOrder.setStatus(8);
			int va = tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
			if(va==0){
				throw new Exception();
			}
			// 修改商品信息
			TbCart cart = tbCartMapper.selectByPrimaryKey(Long.parseLong(tbOrder.getCartId()));
			TbItem tbItem = tbItemMapper.selectByPrimaryKey(cart.getPid());
			tbItem.setNum(tbItem.getNum()-Integer.parseInt(cart.getNum()));
			tbItem.setShiyong(tbItem.getShiyong()+Integer.parseInt(cart.getNum()));
			tbItem.setUpdated(new Date());
			TbItemExample itemExample = new TbItemExample();
			TbItemExample.Criteria itemcriteria = itemExample.createCriteria();
			itemcriteria.andIdEqualTo(tbItem.getId());
			int val = tbItemMapper.updateByExampleSelective(tbItem, itemExample);
			if(val==0){
				throw new Exception();
			}
		}
		if(errorIdlist.size()>0){
			return "商品"+errorIdlist.toString()+"不可以执行退款操作";
		}else{
			return "OK";
		}

	}

	@Override
	public List<TbMUser> getAllSender() {
		TbMUserExample mUserExample = new TbMUserExample();
		TbMUserExample.Criteria muserCriteria = mUserExample.createCriteria();
		muserCriteria.andRoleEqualTo("3");
		
		List<TbMUser>  muserlist= tbMUserMapper.selectByExample(mUserExample);
		return muserlist;
	}

	@Override
	public TaotaoResult selectCartInfo(Long cartId) {
		TbCart tbcart =tbCartMapper.selectByPrimaryKey(cartId);
		// TODO Auto-generated method stub
		return TaotaoResult.ok(tbcart);
	}
}
